<script setup>
import { computed, defineEmits, defineProps, nextTick, reactive, ref, watch } from 'vue'
import { Refresh, Search } from '@element-plus/icons-vue'
import { debounce, deepClone } from '@/utils'

/**
 * 使用说明
 * field: 字段名
 * type: select / input / daterange / datetimernage / inputrange / switch
 * defaultShow: 是否默认显示（在折叠状态下）
 * default: 默认值
 * multiple: 是否多选
 */

const props = defineProps({
  searchConfig: {
    type: Array,
    default: () => [],
  },
  labelStyle: {
    type: Object,
    default: () => ({}),
  },
})

const emits = defineEmits(['search'])

const reactiveData = reactive({
  searchForm: {},
})

const searchArea = ref(null)
const configList = ref([])
const isCollapse = ref(true)
let cloneForm = {}

const isShowCollapse = computed(() => {
  if (isCollapse.value) {
    return props.searchConfig.length !== configList.value.length
  }
  else {
    return true
  }
})

const defaultList = computed(() => props.searchConfig.filter(item => item.defaultShow))

const shortcuts = [
  {
    text: '近七天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

window.onresize = debounce(() => {
  setSearchNumber()
}, 20)

function handleCollapse() {
  isCollapse.value = !isCollapse.value
  setSearchNumber()
}

async function setSearchNumber() {
  await nextTick()
  configList.value = []
  console.log('defaultList',defaultList.value)
  // 获取 searchArea 宽度
  if (isCollapse.value && props.searchConfig.length >= 4) {
    await nextTick(() => {
      // 如果是折叠状态
      if (searchArea.value) {
        const width = searchArea.value.clientWidth - 250
        let sumWidth = 0
        defaultList.value.forEach((item) => {
          if (item.width && (sumWidth + item.width < width)) {
            configList.value.push(item)
            sumWidth += item.width
          }
        })
      }
    })
  }
  else {
    // 如果是展开状态
    configList.value = props.searchConfig
  }
}

function handleSearch(type) {
  emits('search', reactiveData.searchForm, type)
}

function resetForm() {
  reactiveData.searchForm = deepClone(cloneForm)
  handleSearch('reset')
}

function init() {
  reactiveData.searchForm = {}
  props.searchConfig.forEach((item) => {
    if (item.default !== undefined) {
      reactiveData.searchForm[item.field] = item.default
    }
    item.width = ['daterange', 'datetimerange'].includes(item.type) ? 480 : 240
  })
  console.log(props.searchConfig)
  cloneForm = deepClone(reactiveData.searchForm)
  setSearchNumber()
}

init()

watch(() => props.searchConfig, () => {
  init()
})
</script>

<template>
  <div class="search-box">
    <div ref="searchArea" class="search-area !grid grid-cols-3 gap-4 2xl:grid-cols-4">
      <div v-for="(item, index) in configList" :key="index" class="search-item">
        <span :style="item.labelStyle || labelStyle ">{{ item.label }}</span>
        <template v-if="item.type === 'select'">
          <el-select
            v-model="reactiveData.searchForm[item.field]"
            clearable
            :placeholder="item.placeholder || `请选择${item.label}`"
            :multiple="item.multiple === undefined ? false : item.multiple"
            collapse-tags
            :disabled="item.disabled"
            filterable
          >
            <template v-if="item.options && Array.isArray(item.options.data)">
              <el-option
                v-for="s in item.options?.data"
                :key="s[item.options?.value || 'value']"
                :label="s[item.options?.label || 'label']"
                :value="s[item.options?.value || 'value']"
              />
            </template>
          </el-select>
        </template>
        <template v-else-if="item.type === 'input'">
          <el-input
            v-model="reactiveData.searchForm[item.field]"
            clearable
            :placeholder="item.placeholder || `请输入${item.label}`"
            :disabled="item.disabled"
          />
        </template>
        <template v-else-if="['daterange', 'datetimerange'].includes(item.type)">
          <el-date-picker
            v-model="reactiveData.searchForm[item.field]"
            :type="item.type"
            unlink-panels
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :disabled="item.disabled"
            :value-format="item.valueFormat || 'YYYY-MM-DD hh:mm:ss'"
          />
        </template>
        <template v-else-if="item.type === 'inputrange'">
          <input-range v-model="reactiveData.searchForm[item.field]" clearable />
        </template>
        <template v-else-if="item.type === 'switch'">
          <el-switch
            v-model="reactiveData.searchForm[item.field]"
            :active-value="item.activeValue === undefined ? true : item.activeValue"
            :inactive-value="item.inactiveValue === undefined ? false : item.inactiveValue"
            :active-text="item.activeText"
            :inactive-text="item.inactiveText"
          />
        </template>
        <template v-else-if="item.type === 'custom'">
          <slot :name="item.field" />
        </template>
      </div>
      <div class="btn-box">
        <el-button type="primary" @click="handleSearch('search')">
          筛选
          <el-icon class="el-icon--right">
            <Search />
          </el-icon>
        </el-button>
        <el-button plain type="primary" @click="resetForm">
          重置
          <el-icon class="el-icon--right">
            <Refresh />
          </el-icon>
        </el-button>
        <template v-if="searchConfig.length > 4">
          <el-button v-if="isShowCollapse" text @click="handleCollapse">
            <span class="flex-box">
              {{ isCollapse ? '展开' : '收起' }}
              <el-icon
                class="el-icon--right icon-arrow"
                :style="{ transform: isCollapse ? 'rotate(0deg)' : 'rotate(180deg)' }"
              />
            </span>
          </el-button>
        </template>
      </div>
    </div>
    <!--    <div class="operate-box"> -->
    <!--      <slot /> -->
    <!--    </div> -->
  </div>
</template>

<style lang="scss" scoped>
.search-box {
  display: flex;

  .search-area {
    flex-grow: 1;
    display: flex;
    align-items: center;
    height: auto;
    overflow: hidden;

    .search-item {
      margin: 5px 10px;
      display: flex;
      align-items: center;

      & > span {
        text-align: right;
        margin-right: 10px;
        flex-shrink: 0;
        font-size: 14px;
        color: var(--el-text-color);
      }

      ::v-deep(.el-input__inner) {
        width: 150px;
      }

      ::v-deep(.el-range-editor.el-input__inner) {
        width: 390px;
      }

      ::v-deep(.el-switch) {
        height: 32px;
        width: 150px;
      }
    }

    .btn-box {
      flex-shrink: 0;
      margin-left: 10px;
      display: flex;
      align-items: center;
      //grid-column: 4 / -1;
      .el-button {
        margin-right: 10px;
      }

      .icon-arrow {
        transition: transform .5s;
      }
    }
  }

  .operate-box {
    flex-shrink: 0;
    padding: 0 20px;
    margin: 10px;
  }

  .flex-box {
    display: flex;
    align-items: center;
  }
}
</style>
